namespace Vboot.App.My;

/// <summary>
/// DEMO主信息接口
/// </summary>
public class MyDemoMainApi : IDynamicApiController
{
    private readonly MyDemoMainService _service;

    private readonly AssNumMainService _numService;

    public MyDemoMainApi(MyDemoMainService service,
        AssNumMainService numService)
    {
        _service = service;
        _numService = numService;
    }

    /// <summary>
    /// 获取DEMO主信息的分页数据
    /// </summary>
    /// <returns></returns>
    [QueryParameters]
    public async Task<dynamic> Get(string name)
    {
        var pp = XreqUtil.GetPp();
        var items = await _service.repo.Context.Queryable<MyDemoMain, SysOrg, SysOrg>
            ((t, o, o2) => new JoinQueryInfos(
                JoinType.Left, o.id == t.crmid,
                JoinType.Left, o2.id == t.upmid))
            .WhereIF(!string.IsNullOrWhiteSpace(name), t => t.name.Contains(name.Trim()))
            .Select((t, o, o2)
                => new {t.id, t.name, t.addre,t.notes, t.crtim, t.uptim, t.senum, crman = o.name, upman = o2.name})
            .ToPageListAsync(pp.page, pp.pageSize, pp.total);
        return RestPageResult.Build(pp.total.Value, items);
    }

    /// <summary>
    /// 获取单个DEMO的详细信息
    /// </summary>
    /// <param name="id">DEMO ID</param>
    /// <returns></returns>
    [Oplog("DEMO详情查询")]
    public async Task<MyDemoMain> GetOne(string id)
    {
        var main = await _service.SingleAsync(id);
        main.viewers = await _service.repo.Context.Queryable<SysOrg, MyDemoViewer>((o, m) => new JoinQueryInfos(
                JoinType.Inner, o.id == m.oid))
            .Where((o, m) => m.mid == id).ToListAsync();
        main.editors = await _service.repo.Context.Queryable<SysOrg, MyDemoEditor>((o, m) => new JoinQueryInfos(
                JoinType.Inner, o.id == m.oid))
            .Where((o, m) => m.mid == id).ToListAsync();
        if (main.opmid != null)
        {
            main.opman = await _service.repo.Context.Queryable<SysOrg>()
                .Where(it => it.id == main.opmid).SingleAsync();
        }
        main.items = await _service.repo.Context.Queryable<MyDemoItem>()
            .Where(it => it.maiid.Equals(id)).ToListAsync();
        
        main.atts = await _service.repo.Context.Queryable<MyDemoAtt>()
            .Where(it => it.busid.Equals(id)).ToListAsync();
        return main;
    }

    /// <summary>
    /// 新增DEMO
    /// </summary>
    // [MyUnitOfWork]
    public async Task<string> Post(MyDemoMain main)
    {
        main.senum = _numService.getNum("DEMO");
        return await _service.Insertx(main);
    }

    /// <summary>
    /// 修改DEMO
    /// </summary>
    [MyUnitOfWork]
    public async Task<string> Put(MyDemoMain main)
    {
        return await _service.Updatex(main);
    }

    /// <summary>
    /// 删除DEMO
    /// </summary>
    [MyUnitOfWork]
    public async Task Delete(string ids)
    {
        await _service.Deletex(ids);
    }
}